package primenumbers;

import java.math.BigInteger;
import java.util.Queue;

public class PrimesGenerator extends Thread {
	private static final BigInteger TWO = new BigInteger("2");
	private Queue<BigInteger> primes;
	private BigInteger n;
	
	public PrimesGenerator(Queue<BigInteger> queue, BigInteger n) {
		this.primes = queue;
		this.n = n;
	}
	
	@Override
	public void run() {
		BigInteger x = BigInteger.ONE;
		BigInteger root = sqrt(n);
		do {
			x = x.nextProbablePrime();
			if(isPrime(x)) {
				primes.add(x);
			}
		} while (x.compareTo(root) <= 0);
	}

	
	private boolean isPrime(BigInteger x) {
		return true;
	}

	private static BigInteger sqrt(BigInteger n) {
		BigInteger min = BigInteger.ONE;
		BigInteger max = n.divide(TWO);

		BigInteger d = null, x;

		while (max.subtract(min).compareTo(BigInteger.ONE) > 0) {
			d = max.add(min).divide(TWO);
			x = d.multiply(d);

			if (x.equals(n)) {
				return d;
			}

			if (x.compareTo(n) < 0) {
				min = d;
			} else {
				max = d;
			}
		}

		return d;
	}
}
